import sys
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel
from PyQt5.QtWidgets import QApplication, QDialog, \
    QTableView, QPushButton, QAbstractItemView,QHBoxLayout,QVBoxLayout,QLabel
from PyQt5.QtCore import Qt, QModelIndex, QItemSelectionModel,pyqtSlot
from PyQt5.QtGui import QIcon

# 自定义一个子类来重写 data 方法
class CustomSqlTableModel(QSqlTableModel):
    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.TextAlignmentRole:
            return Qt.AlignCenter  # 设置文本居中显示
        return super().data(index, role)

class ProductionRecordDialog(QDialog):
    def __init__(self, db, table_name, mold_life,is_eng):
        super().__init__()
        self.setWindowIcon(QIcon('resources/mainico.png'))
        self.db = db
        self.table_name = table_name
        self.mold_life=mold_life
        self.is_eng=is_eng
        self.production_res=f''
        self.initUI()

    def initUI(self):
        self.setWindowTitle(f'{self.table_name}')
        self.setFixedSize(800, 400)
        self.setStyleSheet("""
                            QWidget {
                                background-color: #f0f0f0;
                            }
                            QLabel {
                                font-size: 20px;
                                color: #333;
                                font-weight: bold;  /* 设置标签字体加粗 */
                            }
                            QPushButton {
                                height: 35px;
                                background-color: #ab7BFF;
                                color: white;
                                border: none;
                                border-radius: 3px;
                                font-size: 20px;
                                font-weight: bold;  /* 设置按钮字体加粗 */
                            }
                            QPushButton:hover {
                                background-color: #0056b3;
                            }
                        """)
        # 创建表格视图
        self.table_view = QTableView()
        self.table_view.setSelectionBehavior(QAbstractItemView.SelectItems)
        self.table_view.setSelectionMode(QAbstractItemView.SingleSelection)
        self.table_view.setAlternatingRowColors(True)
        self.table_view.verticalHeader().setDefaultSectionSize(40)
        self.table_view.horizontalHeader().setDefaultSectionSize(150)

        self.model = CustomSqlTableModel(self, self.db)
        self.model.setTable(self.table_name)  # 设置数据表
        self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)  # 数据保存方式，OnManualSubmit, OnRowChange
        self.model.select()  # 获取所有的数据
        self.__getFieldNames()

        self.table_view.setModel(self.model)
        self.model.setHeaderData(self.fldNum["id"], Qt.Horizontal, "id")
        if self.is_eng:
            self.model.setHeaderData(self.fldNum["start_date"], Qt.Horizontal, "start_date")
            self.model.setHeaderData(self.fldNum["end_date"], Qt.Horizontal, "end_date")
            self.model.setHeaderData(self.fldNum["machine"], Qt.Horizontal, "machine")
            self.model.setHeaderData(self.fldNum["production_length"], Qt.Horizontal, "Output/10km")
        else:
            self.model.setHeaderData(self.fldNum["start_date"], Qt.Horizontal, "起始日期")
            self.model.setHeaderData(self.fldNum["end_date"], Qt.Horizontal, "结束日期")
            self.model.setHeaderData(self.fldNum["machine"], Qt.Horizontal, "机台")
            self.model.setHeaderData(self.fldNum["production_length"], Qt.Horizontal, "产量/万米")

        self.selModel = QItemSelectionModel(self.model)  # 选择模型
        self.table_view.setSelectionModel(self.selModel)  # 设置选择模型

        # 创建显示总产量的标签
        para='Total output: 0  10km' if self.is_eng else "总产量: 0 万米"
        self.total_production_label = QLabel(f'{para}')
        
        # 创建按钮
        para='add' if self.is_eng else '增加'
        add_button = QPushButton(f'{para}')
        add_button.clicked.connect(self.add_record)

        para = 'delete' if self.is_eng else '删除'
        delete_button = QPushButton(f'{para}')
        delete_button.clicked.connect(self.delete_record)

        para='save' if self.is_eng else '保存'
        save_button = QPushButton(f'{para}')
        save_button.clicked.connect(self.save_changes)
        
        para = 'exit' if self.is_eng else '退出'
        exit_button = QPushButton(f'{para}')
        exit_button.clicked.connect(self.accept)

        # 布局按钮
        button_layout = QHBoxLayout()
        button_layout.addWidget(add_button)
        button_layout.addWidget(delete_button)
        button_layout.addWidget(save_button)
        button_layout.addWidget(exit_button)

        # 整体布局
        main_layout = QVBoxLayout()
        main_layout.addWidget(self.total_production_label)
        main_layout.addWidget(self.table_view)
        main_layout.addLayout(button_layout)

        self.setLayout(main_layout)
        
        # 更新总产量
        self.update_total_production()
        self.show()

        
    def __getFieldNames(self):  ##获取所有字段名称
        emptyRec = self.model.record()  # 获取空记录，只有字段名
        self.fldNum = {}  # 字段名与序号的字典
        for i in range(emptyRec.count()):
            fieldName = emptyRec.fieldName(i)
            self.fldNum.setdefault(fieldName)
            self.fldNum[fieldName] = i
        print(self.fldNum)
        
    def add_record(self):
        self.model.insertRow(self.model.rowCount(), QModelIndex())  # 在末尾添加一个记录

    def delete_record(self):
        curIndex = self.selModel.currentIndex()  # 获取当前选择单元格的模型索引
        self.model.removeRow(curIndex.row())  # 删除当前行

    def save_changes(self):
        res = self.model.submitAll()
        if res:
            print('更改成功')
            self.update_total_production()

    def update_total_production(self):
        total = 0
        row_count = self.model.rowCount()
        for row in range(row_count):
            index = self.model.index(row, self.model.fieldIndex('production_length'))
            value = self.model.data(index)
            try:
                total += float(value)
            except (ValueError, TypeError):
                continue
        rest_life = self.mold_life-total
        total_production=f"total output: {total:.2f} 10km" if self.is_eng else f"总产量: {total:.2f} 万米"
        if self.is_eng:
            rest_production=f"rest life: {rest_life:.2f} 10km" if self.mold_life else f"The mold life has not been set yet"
        else:
            rest_production = f"剩余寿命: {rest_life:.2f} 万米" if self.mold_life else f"尚未设定模具寿命"
        self.production_res = f"{total_production}    {rest_production}"    # 四个空格
        self.total_production_label.setText(self.production_res)
        
if __name__ == '__main__':
    app = QApplication(sys.argv)

    # 连接数据库
    db = QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName('mold_management.db')
    if not db.open():
        print('无法打开数据库')
        sys.exit(1)

    # 创建对话框
    dialog = ProductionRecordDialog(db, 'production_records')
    dialog.exec_()
    sys.exit(app.exec_())
